<!DOCTYPE html>

<script src="/login/status"></script>
<script>
  if (!isLogin) {
    location.href = '/admin/login.html'
  }
</script>

<html lang="zh-CN">

<head>
  <meta charset="utf-8">
  <title>Users &laquo; Admin</title>
  <link rel="stylesheet" href="/assets/vendors/bootstrap/css/bootstrap.css">
  <link rel="stylesheet" href="/assets/vendors/font-awesome/css/font-awesome.css">
  <link rel="stylesheet" href="/assets/vendors/nprogress/nprogress.css">
  <link rel="stylesheet" href="/assets/css/admin.css">
  <script src="/assets/vendors/nprogress/nprogress.js"></script>
</head>

<body>
  <script>NProgress.start()</script>

  <div class="main">
    <nav class="navbar">
      <button class="btn btn-default navbar-btn fa fa-bars"></button>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="profile.html"><i class="fa fa-user"></i>个人中心</a></li>
        <li><a id="logoutBtn" href="javascript:;"><i class="fa fa-sign-out"></i>退出</a></li>
      </ul>
    </nav>
    <div class="container-fluid">
      <div class="page-title">
        <h1>用户</h1>
      </div>
      <!-- 有错误信息时展示 -->
      <!-- <div class="alert alert-danger">
        <strong>错误！</strong>发生XXX错误
      </div> -->
      <div class="row">
        <!-- 添加/修改用户表单盒子 -->
        <div class="col-md-4" id="formBox"></div>
        <div class="col-md-8">
          <div class="page-action">
            <!-- show when multiple checked -->
            <a id="batchDelBtn" class="btn btn-danger btn-sm" href="javascript:;" disabled>批量删除</a>
          </div>
          <table class="table table-striped table-bordered table-hover">
            <thead>
              <tr>
                <th class="text-center" width="40"><input id="checkAll" type="checkbox"></th>
                <th class="text-center" width="80">头像</th>
                <th>邮箱</th>
                <th>昵称</th>
                <th>状态</th>
                <th>角色</th>
                <th class="text-center" width="100">操作</th>
              </tr>
            </thead>
            <!-- 用户列表信息渲染地 -->
            <tbody id="userListBox"></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="aside">
    <div class="profile">
      <img class="avatar" src="/uploads/avatar.jpg">
      <h3 class="name">Coder</h3>
    </div>
    <ul class="nav">
      <li>
        <a href="index.html"><i class="fa fa-dashboard"></i>仪表盘</a>
      </li>
      <li>
        <a href="#menu-posts" class="collapsed" data-toggle="collapse">
          <i class="fa fa-thumb-tack"></i>文章<i class="fa fa-angle-right"></i>
        </a>
        <ul id="menu-posts" class="collapse">
          <li><a href="posts.html">所有文章</a></li>
          <li><a href="post-add.html">写文章</a></li>
          <li><a href="categories.html">分类目录</a></li>
        </ul>
      </li>
      <li>
        <a href="comments.html"><i class="fa fa-comments"></i>评论</a>
      </li>
      <li class="active">
        <a href="users.html"><i class="fa fa-users"></i>用户</a>
      </li>
      <li>
        <a href="#menu-settings" class="collapsed" data-toggle="collapse">
          <i class="fa fa-cogs"></i>设置<i class="fa fa-angle-right"></i>
        </a>
        <ul id="menu-settings" class="collapse">
          <li><a href="slides.html">图片轮播</a></li>
          <li><a href="settings.html">网站设置</a></li>
        </ul>
      </li>
    </ul>
  </div>

  <script src="/assets/vendors/jquery/jquery.js"></script>
  <script src="/assets/vendors/bootstrap/js/bootstrap.js"></script>
  <script>NProgress.done()</script>
  <script src="/assets/vendors/art-template/template-web.js"></script>
  <script type="text/html" id="addUserFormTpl">
    <form id="addUserForm">
      <h2>添加新用户</h2>
      <div class="form-group">
        <label>头像</label>
        <div class="form-group">
          <label class="form-image">
            <input id="avatar" type="file">
            <img id="previewImg" src="{{ avatar || '/assets/img/default.png' }}">
            <i class="mask fa fa-upload"></i>
            <input id="hiddenAvatar" type="hidden" name="avatar" value="{{ avatar || '' }}">
          </label>
        </div>
      </div>
      <div class="form-group">
        <label>邮箱</label>
        <input class="form-control" type="email" placeholder="请输入邮箱" name="email">
      </div>
      <div class="form-group">
        <label>昵称</label>
        <input class="form-control" type="text" placeholder="请输入昵称" name="nickName">
      </div>
      <div class="form-group">
        <label>密码</label>
        <input class="form-control" type="text" placeholder="请输入密码" name="password">
      </div>
      <div class="form-group">
        <div class="radio-inline">
          <label><input type="radio" name="status" value="0">未激活</label>
        </div>
        <div class="radio-inline">
          <label><input type="radio" name="status" value="1">激活</label>
        </div>
      </div>
      <div class="form-group">
        <div class="radio-inline">
          <label><input type="radio" name="admin">超级管理员</label>
        </div>
        <div class="radio-inline">
          <label><input type="radio" name="normal">普通用户</label>
        </div>
      </div>
      <div class="form-group">
        <input class="btn btn-primary" type="submit" value="添加">
        <input class="btn btn-primary" type="reset" value="取消">
      </div>
    </form>
  </script>

  <script type="text/html" id="editUserFormTpl">
    <form id="editUserForm" data-id="{{ _id }}">
      <h2>修改用户({{ nickName }})</h2>
      <div class="form-group">
        <label>头像</label>
        <div class="form-group">
          <label class="form-image">
            <input id="avatar" type="file">
            <img id="previewImg" src="{{ avatar || '/assets/img/default.png' }}">
            <i class="mask fa fa-upload"></i>
            <input id="hiddenAvatar" type="hidden" name="avatar" value="{{ avatar || '' }}">
          </label>
        </div>
      </div>
      <div class="form-group">
        <label>邮箱</label>
        <input class="form-control" type="email" placeholder="请输入邮箱" name="email" value="{{ email }}" disabled>
      </div>
      <div class="form-group">
        <label>昵称</label>
        <input class="form-control" type="text" placeholder="请输入昵称" name="nickName" value="{{ nickName }}">
      </div>
      <div class="form-group">
        <div class="radio-inline">
          <label><input type="radio" name="status" value="0" {{ status === 0 ? 'checked' : '' }}>未激活</label>
        </div>
        <div class="radio-inline">
          <label><input type="radio" name="status" value="1" {{ status === 1 ? 'checked' : '' }}>激活</label>
        </div>
      </div>
      <div class="form-group">
        <div class="radio-inline">
          <label><input type="radio" name="role" value="admin" {{ role === 'admin' ? 'checked' : '' }}>超级管理员</label>
        </div>
        <div class="radio-inline">
          <label><input type="radio" name="role" value="normal" {{ role === 'normal' ? 'checked' : '' }}>普通用户</label>
        </div>
      </div>
      <div class="form-group">
        <input class="btn btn-primary" type="submit" value="提交">
        <input class="btn btn-default reset" type="button" value="重置" data-id="{{ _id }}">
        <input class="btn btn-danger cancel" type="button" value="取消">
      </div>
    </form>
  </script>

  <script type="text/html" id="userList">
    {{ each data v }}
    <tr>
      <td class="text-center"><input type="checkbox" data-id="{{ v._id }}"></td>
      <td class="text-center"><img class="avatar" src="{{ v.avatar ? v.avatar : '/assets/img/default.png' }}"></td>
      <td>{{ v.email }}</td>
      <td>{{ v.nickName }}</td>
      <td>{{ [ '未激活', '激活' ][ v.status ] }}</td>
      <td>{{ v.role === 'admin' ? '超级管理员' : '普通用户' }}</td>
      <td class="text-center">
        <a href="javascript:;" class="btn btn-default btn-xs edit" data-id="{{ v._id }}">编辑</a>
        <a href="javascript:;" class="btn btn-danger btn-xs del" data-id="{{ v._id }}">删除</a>
      </td>
    </tr>
    {{ /each }}
  </script>

  <script>
    $(() => {
      // 获取渲染添加/修改用户的容器
      const $formBox = $('#formBox')
      // 获取用户列表容器
      const $userListBox = $('#userListBox')
      // 添加用户表单
      const $addUserForm = $('#addUserForm')
      // 获取全选input
      const $checkAll = $('#checkAll')
      // 批量删除按钮
      const $batchDelBtn = $('#batchDelBtn')
      // 存储用户列表信息
      let userArr = []

      // 渲染添加用户表单
      const renderAddUserForm = () => {
        $formBox.html(template('addUserFormTpl'))
      }
      renderAddUserForm()
      // 渲染编辑用户表单
      const renderEditUserForm = (user) => {
        $formBox.html(template('editUserFormTpl', user))
      }
      // 渲染用户列表
      const renderUserList = () => {
        $userListBox.html(template('userList', { data: userArr }))
      }

      $.ajax({
        type: 'GET',
        url: '/users',
        success(res) {
          userArr = res
          renderUserList()
        }
      })

      // 当头像文件上传成功，触发事件
      $formBox.on('change', '#avatar', ({ target }) => {
        const formData = new FormData()
        // 这个键名，决定了响应数据中图片地址的键名
        formData.append('avatar', target.files[0])
        $.ajax({
          type: 'POST',
          url: '/upload',
          data: formData, // 默认情况下，jq的ajax方法会将data数据处理为urlencoded的格式
          // 是否要处理data，默认true，由于我们在这里传递的是一个FormData对象数据，所以不需要处理
          processData: false,
          // 默认是urlencoded的内容类型，由于我们传递的是一个FormData对象，这个对象中自带了内容类型，所以我们不需要让jq的ajax方法指定了
          contentType: false,
          success(res) {
            const url = res[0].avatar
            $('#previewImg').attr('src', url)
            $('#hiddenAvatar').val(url)
          }
        })
      })

      // 给添加用户表单提交绑定事件
      $formBox.on('submit', '#addUserForm', ({ target }) => {
        const data = $(target).serialize()
        $.ajax({
          type: 'POST',
          url: '/users',
          data,
          success(res) {
            userArr.unshift(res)
            renderUserList()
            renderAddUserForm()
          },
          error(res) {
            alert('添加失败，请稍后再试')
          }
        })
        // 阻止表单默认行为
        return false
      })

      // 给用户列表每一条信息的编辑按钮绑定事件 将对应的用户数据连同修改用户表单渲染在旁边
      $userListBox.on('click', '.edit', ({ target }) => {
        const user = userArr.find(v => v._id === target.dataset.id)
        renderEditUserForm(user)
      })

      // 用户列表信息删除事件
      $userListBox.on('click', '.del', ({ target }) => {
        const id = target.dataset.id
        const user = userArr.find(v => v._id === id)
        if(confirm(`您确定要删除${user.nickName}这个用户吗？`)){
          $.ajax({
            type: 'DELETE',
            url: `/users/${id}`,
            success(res) {
              userArr = userArr.filter(v => v._id !== id)
              renderUserList()
            }
          })
        }
      })

      // 给修改用户表单提交绑定事件
      $formBox.on('submit', '#editUserForm', ({ target }) => {
        const data = $(target).serialize()
        $.ajax({
          type: 'PUT',
          url: `/users/${target.dataset.id}`,
          data,
          success(res) {
            const index = userArr.findIndex(v => v._id === res._id)
            userArr.splice(index, 1, res)
            renderUserList()
            renderAddUserForm()
          }
        })
        return false
      })

      // 点击编辑表单下的重置按钮时
      $formBox.on('click', '#editUserForm .reset', ({ target }) => {
        const user = userArr.find(v => v._id === target.dataset.id)
        renderEditUserForm(user)
      })
      // 编辑表单下取消按钮
      $formBox.on('click', '#editUserForm .cancel', () => {
        renderAddUserForm()
      })

      // 全选input事件
      $checkAll.change(({ target }) => {
        const checked = $(target).prop('checked')
        $('#userListBox :checkbox').prop('checked', checked)
        $batchDelBtn.attr('disabled', !checked)
      })

      $userListBox.on('change', ':checkbox', () => {
        const checkLength = $('#userListBox :checkbox:checked').length
        // 判断是否用户被全部选中
        $checkAll.prop('checked', userArr.length === checkLength)
        // 当用户一个都没选中时 禁用批量删除按钮
        $batchDelBtn.attr('disabled', checkLength === 0)
      })

      $batchDelBtn.click(() => {
        // 做这个判断是因为禁用也能触发点击事件，因为它是一个a标签，如果是一个input或者button标签，禁用后就不会触发
        if ($batchDelBtn.attr('disabled') !== undefined) return
        let idArr = []
        $('#userListBox :checkbox:checked').each((i, v) => {
          idArr.push(v.dataset.id)
        })
        if(!confirm(`您确定要删除这${idArr.length}个用户吗？`)) return

        $.ajax({
          type: 'DELETE',
          url: `/users/${idArr.join('-')}`,
          success(res) {
            userArr = userArr.filter(v => !idArr.includes(v._id))
            renderUserList()
          }
        })
      })
    })
  </script>
</body>

</html>